import React, { Component, FC, useEffect, useRef, useState } from 'react'
import { changeSize, remote } from '@utils/electron'
import { Button, Layout, Divider, Card, List, Modal, Tabs, message, PageHeader } from 'antd'
import { history } from 'umi'
// @ts-ignore
import logo from '../../assets/image/icon.png'
import $ from '@utils/jquery-vendor.ts'
import 'ztree'
import Icon, { PlusCircleOutlined, CloseCircleOutlined, ArrowLeftOutlined } from '@ant-design/icons/lib'
import { Config } from '@utils/Constants'
import 'ztree/css/metroStyle/metroStyle.css'
import { fetchProjectFileTreeApi, projectDetail } from '@/services/project'
import FileForm from '../components/FileForm'
import { deleteProFile, saveFile } from '@/services/proFile'
import ModuleConfig from '@pages/components/ModuleConfig'
import DetailInfo from '@pages/components/DetailInfo'
import TableGenConfig from '@pages/components/TableGenConfig'
import MicroConfig from '@pages/components/MicroConfig'
import VoView from '../VoView/VoView'
import ControllerView from '@pages/ControllerView/ControllerView'
import  './style.less'

const { Header, Sider, Content } = Layout
const confirm = Modal.confirm
const TabPane = Tabs.TabPane

interface ProjectDetailProps {
  location:any,
}

const ProjectDetail: FC<ProjectDetailProps> = (props) => {

  let ztreeIndex = 0
  let fileTree = null
  // let rightClickNode: any = {}// 右击节点
  let fileFormRef: any
  let refs: any = useRef()
  const { location: { query: { projectId, projectName,comment } } } = props

  const [rightClickNode, setRightClickNode] = useState<any>({})
  const [projectTree, setProjectTree] = useState<any>([])
  const [tabPanes, setTabPanes] = useState<any>([])
  const [proDetail, setProDetail] = useState<any>({})
  const [openStats, setOpenStats] = useState<any>({})
  const [rightMenu, setRightMenu] = useState<any>({ display: 'none' })
  const [activeKey, setActiveKey] = useState('')
  const [rightClickMicroId, setRightClickMicroId] = useState('')
  const [showFileForm, setShowFileForm] = useState(false)

  // 添加文件
  const [visible, setVisible] = useState<boolean>(false)
  const showFileVisible = (flag: boolean) => {
    setVisible(flag)
  }

  const fileHandleOk = (data: any) => {
    data.project_id = projectId;
    data.micro_id = rightClickNode.microId;
    saveFile(data).then((res) => {
      if (res.code === 10000) {
        message.success("文件添加成功！");
        fetchProjectFileTree();
      }else {
        message.error("文件添加失败，请稍后重试！");
      }
    })
    setVisible(false)
  }

  // 模块管理
  const [moduleVis,setModuleVis] = useState<boolean>(false);
  const showModuleCif = (flag:boolean) => {
    setModuleVis(flag);
  }

  // 项目详情
  const [detailVis,setDetailVis] = useState<boolean>(false)
  const showDetail = (flag:boolean) => {
    setDetailVis(flag)
  }

  // 数据库表配置
  const [tabCifVis,setTabCifVis] = useState<boolean>(false);
  const showTableConfig = (flag:boolean) => {
    setTabCifVis(flag);
  }

  // 微服务管理
  const [microCifVis,setMicroCigVis] = useState<boolean>(false)
  const showMicroCif = (flag:boolean) => {
    setMicroCigVis(flag);
  }

  useEffect(() => {
    changeSize(1700, 1000, '项目配置')
    $(document).bind('click', function(e: any) {
      setRightMenu({ display: 'none' })
    })

    projectDetail(projectId).then((res) => {
      if (res.code === 10000) {
        setProDetail(res.data)
      }
    })
    fetchProjectFileTree()
  }, [])

  const fetchProjectFileTree = () => {
    // 获取文件
    let fileTreeRet = fetchProjectFileTreeApi(projectId)
    fileTreeRet.then((res) => {
      setProjectTree(res.data)
    })
  }

  const removeSelectedFile = () => {
    // 判断不可删除文件
    if ('vo' == rightClickNode.fileType) {
      var ret = Config.VO_IGNORE.findIndex((element) => (element == rightClickNode.name.split('.')[0]))
      if (ret > -1) {
        Modal.error({
          title: '错误提示',
          content: '非自定义创建无法删除！'
        })
        return
      }
    }
    console.log(rightClickNode)
    confirm({
      title: '删除【' + rightClickNode.name + '】 文件?',
      content: '请确认是否删除？',
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk() {

        if (rightClickNode.fileType == 'package') {
          Modal.error({
            title: '错误提示',
            content: '非自定义创建无法删除！'
          })
          return
        }

        var newTreeData: any = []
        for (var i = 0; i < projectTree.length; i++) {
          if (projectTree[i].id != rightClickNode.id) {
            newTreeData.push(projectTree[i])
          }
        }
        setProjectTree(newTreeData)

        // 调用删除方法
        deleteProFile({ 'id': rightClickNode.fileId }).then((res) => {
          if (res.code === 10000) {
            message.success('文件删除成功！')
          }
        })
      },
      onCancel() {
        console.log('Cancel')
      }
    })
  }

  const showAddFilePanel = () => {
    setRightMenu({ display: 'none' })
    fileFormRef.showFileFormPanel({ fileType: rightClickNode.name }, (ret: any) => {
      if (ret === 'close') {

      } else if (ret == 'add' || ret == 'update') {
        // reload
        fetchProjectFileTree()
      }
    })
  }


  const onChange = (activeKey: string) => {
    setActiveKey(activeKey)
  }

  const onEdit = (targetKey: any, action: string) => {
    if (action == 'remove') {
      remove(targetKey)
    }
  }

  const remove = (targetKey: string) => {

    let lastIndex: any
    tabPanes.forEach((pane: any, i: number) => {
      if ('panel_' + pane.id === targetKey) {
        lastIndex = i - 1
      }
    })
    const tabs = tabPanes.filter((pane: any) => 'panel_' + pane.id !== targetKey)
    if (lastIndex >= 0 && activeKey === targetKey) {
      setActiveKey('panel_' + tabPanes[lastIndex].id)
    }
    setTabPanes(tabs)
  }

  const addTab = (treeNode: any) => {
    const active = 'panel_' + treeNode.id
    var noOpen = true
    for (var i = 0; i < tabPanes.length; i++) {
      if (treeNode.id === tabPanes[i].id) {
        noOpen = false
        break
      }
    }
    if (noOpen) {
      tabPanes.push(treeNode)
      setTabPanes(tabPanes)
    }
    setActiveKey(active)
  }

  let zNodes = projectTree
  // @ts-ignore
  window.zNodes = zNodes

  for (var i = 0; i < zNodes.length; i++) {
    var node = zNodes[i]
    var type = node.fileType
    // 更改图标
    if (type === 'package') {
      node['icon'] = require('../../assets/image/package_off.png')
    } else if (type === 'folder') {
      node['icon'] = require('../../assets/image/package_off.png')
    } else {
      node['icon'] = require('../../assets/image/file.png')
    }

    // open status
    if (openStats[node.id]) {
      node.open = true
    } else if (openStats[node.id] === false) {
      node.open = false
    }

    zNodes[i] = node
  }

  const setting = {
    data: {
      simpleData: {
        enable: true
      }
    },
    callback: {
      onExpand: (event: any, treeId: any, treeNode: any) => {
        openStats[treeNode.id] = true
        setOpenStats(openStats)
      },
      onCollapse: (event: any, treeId: any, treeNode: any) => {
        openStats[treeNode.id] = false
        setOpenStats(openStats)
      },
      onClick: (event: any, treeId: any, treeNode: any) => {
        if (treeNode.fileType === 'package') {
          openStats[treeNode.id] = !openStats[treeNode.id]
          setOpenStats(openStats)
        } else {
          if (treeNode.getParentNode()) {
            openStats[treeNode.getParentNode().id] = true
            addTab(treeNode)
          }
        }
        setRightMenu(rightMenu)
      },
      onRightClick: (event: any, treeId: any, treeNode: any) => { // 右键事件
        if (treeNode) {
          setRightClickMicroId(treeNode.microId)
          setRightClickNode(treeNode)
          setRightMenu({ display: '', left: event.clientX + 'px', top: (event.clientY - 60) + 'px' })
        }
      }
    }
  }

  fileTree = $.fn.zTree.init($(refs.current), setting, zNodes)


  return (
    <Layout>
      <Sider
        style={{ backgroundColor: '#fff',height:900 }}
        width={330}
        trigger={null}
        collapsible
        collapsed={false}
      >
        <PageHeader
          onBack={() => history.push('/')}
          title={projectName}
          subTitle={comment}
        />
        {/*<div style={{ fontSize: 23, paddingTop: 5,marginLeft:20, paddingBottom: 5 }}>*/}
        {/*  <span><ArrowLeftOutlined /></span>*/}
        {/*  /!*<img src={logo} width={40}/>*!/*/}
        {/*  <span style={{ marginLeft: 10,fontWeight:500 }}>{projectName}</span>*/}
        {/*</div>*/}
        {/*<Divider style={{ margin: 0 }}/>*/}

        <div style={{ background: 'white', overflow: 'auto', height: '100%', position: 'relative' }}>

          <div className="ztree" ref={refs} id={`ztree_${ztreeIndex++}`}></div>

          <div className="right-menu-panel"
               style={{ padding: '10px', width: '240px', position: 'absolute', ...rightMenu }}>
            <List
              style={{ backgroundColor: 'white', width: 150 }}
              size="small"
              bordered
            >
              <List.Item><a onClick={() => showFileVisible(true)}><PlusCircleOutlined/>&nbsp;添加文件</a></List.Item>
              <List.Item><a onClick={removeSelectedFile}><CloseCircleOutlined/>&nbsp;删除文件</a></List.Item>
            </List>
          </div>
        </div>
      </Sider>
      <Layout>
        <Header style={{ backgroundColor: '#fff', textAlign: 'right', height: 70, lineHeight: '70px' }}>
          {/*<Button type='primary' size='small' style={{ marginRight: 8 }} onClick={() => history.push('/')}>go*/}
          {/*  back</Button>*/}
          <Button type='primary' size='small' style={{ marginRight: 8 }} onClick={() =>showModuleCif(true)}>模块管理</Button>
          <Button type='primary' size='small' style={{ marginRight: 8 }} onClick={() =>showDetail(true)}>项目详情</Button>
          <Button type='primary' size='small' style={{ marginRight: 8 }} onClick={() =>showTableConfig(true)}>数据库表管理</Button>
          {proDetail.pro_type === 'micro' &&
          <Button type='primary' size='small' onClick={()=>showMicroCif(true)}>微服务管理</Button>}
        </Header>
        <Content>
          {/* 标签 */}
          <div>
            <Tabs
              hideAdd
              size='small'
              onChange={onChange}
              activeKey={activeKey}
              type="editable-card"
              onEdit={onEdit}
            >
              {tabPanes.map((pane: any) =>
                <TabPane style={{ margin: 0 }} tab={pane.name} key={'panel_' + pane.id}>
                  {pane.fileType === 'controller'
                    ?
                    <ControllerView projectId={projectId} fileId={pane.fileId} />
                    :
                    (pane.fileType === 'vo'
                        ?
                        <VoView fileId={pane.fileId} projectId={projectId} />
                        :
                        ''
                    )
                  }
                </TabPane>)}
            </Tabs>
          </div>
        </Content>
      </Layout>
      {/* 添加文件弹出框 */}
      <FileForm fileType={rightClickNode.name} microId={rightClickNode.microId} visible={visible} projectId={projectId}
                showFileVisible={showFileVisible} fileHandleOk={fileHandleOk}/>
      {/* 模块管理 */}
      <ModuleConfig isMicro={proDetail.pro_type === 'micro'} visible={moduleVis} onClose={showModuleCif} projectId={projectId}/>
      {/*项目详情 */}
      <DetailInfo visible={detailVis} onClose={showDetail} projectId={projectId} />
      {/* 数据库表配置 */}
      <TableGenConfig visible={tabCifVis} onClose={showTableConfig} projectId={projectId} />
      {/* 微服务*/}
      <MicroConfig visible={microCifVis} onClose={showMicroCif} projectId={projectId} />
    </Layout>
  )
}


export default ProjectDetail
